package com.gaoyi.crm.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import java.io.File;

public class AppUtil {
    private static Context mContext;

    public static void initContext(Context context) {
        mContext = context;
    }

    public static Context getContext() {
        if (mContext == null) {
            throw new UnsupportedOperationException("Context 未初始化");
        }
        return mContext;
    }

    /**
     * 获取当前APP版本号
     */
    public static String getVersion() {
        try {
            PackageManager packageManager = mContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 安装apk
     */
    public static void installApk(Context activity, File apkFile) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".provider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(apkFile);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        activity.startActivity(intent);
    }

    public static String getIMEI() {
        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Activity.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return "";
        }
        String imei = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            try {
                imei = tm.getMeid();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (TextUtils.isEmpty(imei)) {
                imei = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                imei = tm.getImei();
            }
            if (TextUtils.isEmpty(imei)) {
                imei = tm.getDeviceId();
            }
        }
        return imei;
    }
}
